package com.mos.iot.mqtt.listener.converter;

import cn.hutool.core.util.ReflectUtil;
import lombok.RequiredArgsConstructor;

import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
public enum MessageConverterRegistry {

    INSTANCE;

    private final Map<Class<? extends MessageConverter>, MessageConverter> MESSAGE_CONVERTER_CACHE = new HashMap<>();

    public void add(Class<? extends MessageConverter> messageConverterClass) {
        MESSAGE_CONVERTER_CACHE.computeIfAbsent(messageConverterClass, ReflectUtil::newInstance);
    }

    public MessageConverter getMessageConverter(Class<? extends MessageConverter> messageConverterClass) {
        add(messageConverterClass);
        return MESSAGE_CONVERTER_CACHE.get(messageConverterClass);
    }

    public <T> T converter(Class<? extends MessageConverter> messageConverterClass, Object value, Class<T> targetClass) {
        return getMessageConverter(messageConverterClass)
                .convertWithCheck(value, targetClass, null, true);
    }

}
